<template>
  <van-nav-bar
    title="鸟类查询"
    @click-left="routerBack()"
    left-arrow
    :fixed="true"
    :safe-area-inset-top="true"
    :placeholder="true"
  >
    <template v-if="isVip" #right>
      <van-icon
        name="plus"
        @click="showAddBirdAction = true"
        color="#000"
        size="18"
      />
    </template>
  </van-nav-bar>
  <van-search
    v-model="searchValue"
    placeholder="请输入鸟类名称"
    shape="round"
    @search="onSearch"
    @update:model-value="onSearchUpdate"
  />
  <van-tree-select
    v-model:main-active-index="activeIndex"
    v-model:active-id="activeId"

    :items="items"
    @click-item="onClickItem"
    height="85vh"
  />

  <van-action-sheet
    v-model:show="showAddBirdAction"
    cancel-text="取消"
    title="新增一种鸟类吧"
  >
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="newBird.BirdChineseName"
          label="中文名"
          placeholder="请输入鸟类的中文名"
        />
        <van-field
          v-model="newBird.BirdEnglishName"
          label="英文名"
          placeholder="请输入鸟类英文名"
        />

        <van-field
          v-model="newBird.protectionStatus"
          is-link
          readonly
          name="picker"
          label="保护状态"
          placeholder="点击选择鸟类保护状态"
          @click="protectionStatusPicker = true"
        />
        <!-- 上传图片 -->
        <van-field name="uploader" label="鸟类样图上传">
          <template #input>
            <van-uploader
              preview-size="60"
              multiple
              :max-count="6"
              v-model="newBird.imgList"
            />
          </template>
        </van-field>
        <van-field
          v-model="classifyValue"
          is-link
          readonly
          label="分类"
          placeholder="选择分类"
          @click="classifyShow = true"
        />
        <van-popup v-model:show="classifyShow" round position="bottom">
          <van-picker
            :ref="picker"
            :columns="classifyColumns"
            @cancel="classifyShow = false"
            @confirm="onClassifyConfirm"
            @change="onClassifyChange"
          />
        </van-popup>
        <van-field
          v-model="newBird.distribution"
          rows="1"
          autosize
          label="地理分布"
          type="textarea"
          placeholder="请输入地理分布"
        />
        <van-field
          v-model="newBird.habitat"
          rows="1"
          autosize
          label="栖息环境"
          type="textarea"
          placeholder="请输入鸟类栖息环境"
        />
        <van-field
          v-model="newBird.character"
          rows="1"
          autosize
          label="特征"
          type="textarea"
          placeholder="请输入鸟类特征"
        />
        <!-- 保护级别选择器 -->
        <van-popup v-model:show="protectionStatusPicker" position="bottom">
          <van-picker
            :columns="protectionStatusColumns"
            @confirm="onProtectionStatusColumnsConfirm"
            @cancel="protectionStatusPicker = false"
          />
        </van-popup>
        <!-- 科目属 级联选择 -->
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          增加
        </van-button>
      </div>
    </van-form>
  </van-action-sheet>
</template>
<script>
import { reactive, ref, toRefs } from '@vue/reactivity';
import { useRouter } from 'vue-router';
import { onBeforeMount } from '@vue/runtime-core';
import { useStore } from 'vuex';
import { addBird, upload, getFuzzyquery } from '@/api/interface';
import { Toast } from 'vant';
import tool from '@/utils/tool.js';
export default {
  setup() {
    const picker = ref(null);
    const classifyObj = {};
    const store = useStore();
    const state = reactive({
      // 绑定搜索框输入内容
      searchValue: '',
      // 该用户是vip才可以增加鸟类
      isVip: false,
      // 增加鸟类action
      showAddBirdAction: false,
      // treeSelect的数据
      items: [],
      activeId:-1,
      activeIndex: 0,
      // 科目属
      classifyShow: false,
      classifyColumns: [],
      classifyValue: '',
      // 保护选择器
      protectionStatusPicker: false,
      protectionStatusColumns: ['LC', 'NT', 'VU', 'EN', 'CR', 'EW', 'EX'],
      // 目 选择器的列表
      // 添加新鸟类的准备信息
      newBird: {
        BirdChineseName: '',
        BirdEnglishName: '',
        protectionStatus: '',
        introduction: '',
        imgList: [],
        classification: {
          mu: '',
          ke: '',
        },
        habitat: '',
        behavior: '',
        character: '',
        distribution: '',
      },
    });
    const router = useRouter();
    const routerBack = () => {
      router.go(-1);
    };
    const routerTo = (url) => {
      router.push({
        path: url,
      });
    };
    const onSubmit = async () => {
      const formData = new FormData();
      state.newBird.imgList &&
        state.newBird.imgList.forEach(async (item) => {
          formData.append('file', item.file);
        });

      if (state.newBird.imgList.length != 0) {
        Toast.loading({
          duration: 0,
          forbidClick: true,
          message: '图片上传中',
        });
        await upload(formData).then((res) => {
          state.newBird.imgList = res.data;
          Toast.clear();
        });
      }
      await addBird(state.newBird).then((res) => {
        console.log('newBird', res);
      });
      window.location.href = '/coupe';
    };
    const onProtectionStatusColumnsConfirm = (value) => {
      state.newBird.protectionStatus = value;
      state.protectionStatusPicker = false;
    };
    // classfiy 分类
    const onClassifyChange = (values) => {
      state.classifyColumns[1].values = classifyObj[values[0]];
    };
    const onClassifyConfirm = (e) => {
      state.classifyValue = e[0] + ' - ' + e[1].text;
      state.newBird.classification.mu = e[0];
      state.newBird.classification.ke = e[1].text;
      state.classifyShow = false;
    };
    // tree select
    const onClickItem = (e) => {
      routerTo(`/classify/${state.items[state.activeIndex].text}/${e.text}`);
    };
    // 处理搜索事件
    const onSearch = (e) => {
      console.log(e);
    };
    // 处理搜索框内容变更监听事件
    const onSearchUpdate = tool.throttle(async function (e) {
      await getFuzzyquery({ value: e }).then((res) => {
        console.log('-----------------------------------', res.data);
      });
    }, 1500);

    onBeforeMount(async () => {
      await store.dispatch('_getJsonInfo');
      await store.dispatch('_getUserInfo');
      state.items = store.state.coupeData;
      state.classifyColumns.push({ values: state.items.map((x) => x.text) });

      state.items.forEach((e) => {
        classifyObj[e.text] = e.children;
      });
      state.classifyColumns.push({
        values: classifyObj[state.classifyColumns[0].values[0]],
      });
      state.isVip = store.state.userinfo.Vip.isVip;
    });

    return {
      ...toRefs(state),
      routerBack,
      picker,
      routerTo,
      onSubmit,
      onProtectionStatusColumnsConfirm,
      onClickItem,
      onClassifyConfirm,
      onClassifyChange,
      onSearch,
      onSearchUpdate,
    };
  },
};
</script>
<style lang="less" scoped>
.itemContainer {
  column-count: 2;
  column-width: 50%;
  column-gap: 0px;
  padding: 10px 0;
}
::v-deep(.van-sidebar-item--select:before) {
  background-color: rgba(16, 110, 216, 0.769);
}
</style>
